<template>
  <div>
    <div class="search">
    <input v-model="keyWord" class="search-input" type="text" placeholder="请输入名字或者是拼音">
    </div>
    <div class="serch-content" ref="seach" v-show="keyWord">
      <ul>
        <li class="serach-item" v-for="item in list" :key="item.id" @click="handleCityClick(item.name)">{{item.name}}</li>
        <li class="serach-item" v-show="!list.length">没有数据匹配</li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from '@better-scroll/core'
import { mapMutations } from 'vuex'
export default {
  props: {
    cities: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      keyWord: '',
      list: [],
      // 节流
      timer: null
    }
  },
  watch: {
    keyWord () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyWord) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (const i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyWord) != -1 || value.name.indexOf(this.keyWord) != -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  mounted () {
    this.initBscroll()
  },
  methods: {
    // 初始化bscroll
    initBscroll () {
      this.bscroll = new BScroll(this.$refs.seach, {
        click: true
      })
    },
    handleCityClick (city) {
      this.changeCity(city)
      this.$router.push('/home')
    },
    ...mapMutations(['changeCity'])
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/styles/varibles.styl'
  .search
   height 0.72rem
   background-color $bgColor
   padding 0 0.2rem
   .search-input
    box-sizing border-box
    border-radius .1rem
    width 100%
    height 0.62rem
    line-height 0.62rem
    padding 0 0.1rem
    text-align center
    color #666
  .serch-content
   overflow hidden
   width 100%
   position absolute
   top 1.58rem
   left 0
   right 0
   bottom 0
   background-color #fff
   z-index 999
   .serach-item
    line-height .62rem
    padding-left .2rem
    color #666
    border-bottom 0.01rem solid #ccc
</style>
